package com.nida.route;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import cn.sunline.rest.util.Convert;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpResponseStatus;

public abstract class RouteHandler {
    
    private ChannelHandlerContext ctx;
    
    private FullHttpRequest request;
    
    private FullHttpResponse response;
    
    public void excute(ChannelHandlerContext ctx,FullHttpRequest request, FullHttpResponse response){
        this.ctx = ctx;
        this.request = request;
        this.response = response;
        this.handle(this.request, this.response);
    }
    
    public abstract void handle(FullHttpRequest request, FullHttpResponse response);
    
    public void rendJson(Object obj){
        retMsg(ctx, request, obj, HttpResponseStatus.OK, "application/json; charset=UTF-8");
    }
    
    public static void rend404(ChannelHandlerContext ctx, FullHttpRequest req){
        retMsg(ctx, req, "当前请求页面不存在。。。", HttpResponseStatus.NOT_FOUND, "text/html; charset=UTF-8");
    }
    
    private static void retMsg(ChannelHandlerContext ctx, FullHttpRequest req,Object obj
            ,HttpResponseStatus status,String resultContextType){
        ByteBuf content = Convert.Obj2Buf(obj);
        if (content == null) {
            return;
        }
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1,status, content);
        res.headers().set(CONTENT_TYPE, resultContextType);
        HttpHeaderUtil.setContentLength(res, content.readableBytes());
        if (HttpHeaderUtil.isKeepAlive(req)) {
            res.headers().set(CONNECTION, CONNECTION);
            ctx.write(res);
            ctx.flush();
        } else {
            ctx.write(res);
            ctx.flush();
            ctx.channel().writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
